<?php


namespace Middleware;




use Consts\RedisKey;
use Firebase\JWT\JWT;
use Helper\Config;
use Helper\Output;
use Helper\Redis;
use Helper\Reg;

class TokenValidationMiddleware
{
    protected static $instance;

    public static function getInstance()
    {
        if ( !isset(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    public function authWs($request, $response){

        $token = $request->get['token'];
        if (empty($token)) {
            var_dump(' token is null ');
            return false;
        }
        try {

            $jwtConf = Config::getInstance()->get('jwt');
            $decoded = (array)JWT::decode($token, $jwtConf['key'], array('HS256'));


        } catch (\Exception $e) {
            var_dump('错误token:'.$token.$e->getMessage());
            return false;
        }

        return $decoded['data'];

    }

    public function tokenAuth($request, $response)
    {

        $route = $request->server['request_uri'];
        $passRoute = Config::getInstance()->get('pass_route');

        //免检方法则不认证token
        if(!in_array($route,$passRoute)) {
            $token = $request->post['token'];
            if (empty($token)) {
                Output::responseJson(1006);
                return false;
            }
            try {

                $jwtConf = Config::getInstance()->get('jwt');
                $decoded = (array)JWT::decode($token, $jwtConf['key'], array('HS256'));
                //判断是后台还是前台
                if(isset($decoded['data']->user_id)){
                    //验证是不是最新token
                    $serverToken = Redis::getInstance()->get(RedisKey::loginUserToken($decoded['data']->user_id));
                    if(!$serverToken){
                        Output::responseJson(1007);
                        return false;
                    }
                    if($serverToken != $token){
                        Output::responseJson(1007);
                        return false;
                    }

                    Reg::getInstance()->set('user_id', $decoded['data']->user_id);
                    Reg::getInstance()->set('user', $decoded['data']->user);
                }else{

                    Reg::getInstance()->set('customer_id',$decoded['data']->customer_id);
                }


            } catch (\Exception $e) {
                Output::responseJson(500, $e->getMessage());
                return false;
            }
        }

        return true;

    }


}